package com.ilxqx.framework.generator.data;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ilxqx.framework.generator.constant.GenerationConfigConstants;
import com.ilxqx.framework.generator.core.util.TemplateGenerationUtils;
import com.ilxqx.framework.generator.parser.Table;
import com.ilxqx.framework.generator.parser.TableField;
import com.ilxqx.framework.system.po.ItemEntry;

import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 枚举类生成处理
 * @author venus
 */
@ProcessingOrder(2)
public class EnumClassGeneratorDataModelProcessing implements DataModelProcessing {

	/**
	 * 数据模型处理
	 *
	 * @param dataModel 数据模型(其中table为表对象，里面包含你想要的信息)
	 */
	@Override
	public void process(Map<String, Object> dataModel) {
		Table table = (Table) dataModel.get("table");
		for (TableField field : table.getFields()) {
			if (field.getRules().match("enum")) {
				Map<String, String> params = field.getRules().getRule("enum").getParams();
				if (params.isEmpty()) {
					continue;
				}
				// 需要进行生成enum枚举
				this.customData(dataModel, params, field);
				Map<String, String> placeholders = Maps.newHashMap();
				placeholders.put("field", field.getCamelName());
				TemplateGenerationUtils.generateJavaCode(dataModel, table, GenerationConfigConstants.ENUM_TEMPLATE, placeholders);
				TemplateGenerationUtils.generateJavaCode(dataModel, table, GenerationConfigConstants.CONVERTER_TEMPLATE, placeholders);
				this.deleteData(dataModel);
			}
		}
	}

	/**
	 * 生成枚举类前处理一些数据
	 * @param dataModel 数据map
	 * @param params 枚举参数
	 * @param field 枚举字段
	 */
	private void customData(Map<String, Object> dataModel, Map<String, String> params, TableField field) {
		List<ItemEntry> entries = Lists.newArrayList();
		params.forEach((k, v) -> entries.add(new ItemEntry(k, v)));
		// 排序
		entries.sort(Comparator.comparing(ItemEntry::getValue));
		dataModel.put("items", entries);
		dataModel.put("field", field);
	}

	/**
	 * 生成完枚举类之后销毁处理的自定义数据
	 * @param dataModel 数据map
	 */
	private void deleteData(Map<String, Object> dataModel) {
		dataModel.remove("items");
	}

}
